/**
 * Created by yihua on 2017/2/8.
 */

var pictureUrl = '';
$(document).ready(function () {
    //init();
    //initCategory();
    $("#toolbar-add").click(function () {
        $("#myModal").modal("show");
        initCategory('#parent_id', '#myModal');

    });

    var btn = $("#confirm");
    btn.unbind('click').click(function () {
        addGoodsCategory();
    });
    deleteCategory();
    //editCategory();
    initUploadImg("addimg");
    /*
     //initUploadImg("editimg");
     $("#edit_confirm").click(function(){
     var options = {
     url: '/api/goodscategory/editgoodscategory',
     beforeSubmit:  validate,  // pre-submit callback
     success:       showResponse,  // post-submit callback
     dataType:      'json',
     type:          'get',
     data:  {
     'cat_id': $("#edit_category_id").val(),
     'img':pictureUrl
     }
     };
     $("#editCatgoryForm").ajaxSubmit(options)
     $('#editModal').modal("hide");
     });
     */

});

var initSelect2 = function (id, dropdown, data) {
    $(id).select2({
        data: data,
        dropdownParent: $(dropdown),

    });
}

function initCategory(id, dropdown) {
    $.ajax({
        url: '/home/shop/getcategory',
        timeout: 100000,
        type: 'get',
        dataType: 'json',
        async: false,
        data: {},
        success: function (rs) {
            //console.log(rs)
            if (rs.errno != 0) {
                toastr.error(rs.errno);
                return false;
            } else {
                console.log(rs.data)
                initSelect2(id, dropdown, rs.data);
            }
        },
        error: function () {
            toastr.error('系统错误');
        }
    });
}

function deleteCategory() {
    $(".catDel").each(function () {
        //console.log($(this))
        var id = $(this).parent().parent()[0].id;
        $(this).unbind('click').click(function () {
            $("#deleteModal").modal("show");
            $("#delete_confirm").click(function () {
                $.ajax({
                    url: '/api/goods/delelecategory',
                    timeout: 100000,
                    type: 'get',
                    dataType: 'json',
                    data: {
                        'cat_id': id
                    },
                    success: function (rs) {
                        if (rs.errno != 0) {
                            toastr.error(rs.errmsg, '', {positionClass: 'toast-bottom-center'});
                        } else {
                            toastr.success(rs.errmsg, '', {positionClass: 'toast-bottom-center'});
                            window.location.reload();
                        }

                    },
                    error: function () {
                        toastr.error('系统错误', '', {positionClass: 'toast-bottom-center'});
                    }
                });
            });
        });

    });


}

function addGoodsCategory() {
    var options = {
        url: '/goods/addgoodscategory',
        beforeSubmit: validate,  // pre-submit callback
        success: showResponse,  // post-submit callback
        dataType: 'json',
        type: 'post',
        data: {
            'img': pictureUrl
        }
    };
    $("#goodsCatgoryForm").ajaxSubmit(options)

}
function validate(formData, jqForm, options) {
    for (var i = 0; i < formData.length; i++) {
        if (!formData[i].value) {
            if ("file" == formData[i].type) {
                continue;
            }
            //alert('请输入所有选项 ');
            toastr.error('请输入所有选项', '', {positionClass: 'toast-bottom-center'});
            return false;
        }
    }
    console.log(formData)
}


function showResponse(responseText, statusText, xhr, $form) {
    console.log(responseText);
    if (0 !== responseText.errno) {
        toastr.error(responseText.errmsg, '', {positionClass: 'toast-bottom-center'});
    } else {
        toastr.success('成功', '', {positionClass: 'toast-bottom-center'});
        $('#myModal').modal("hide");
        window.location.reload();
    }
}

function initUploadImg(id) {
    $("#" + id).fileinput({
        uploadUrl: "/common/uploadimage", // server upload action
        showUpload: false,
        uploadAsync: true,
        showPreview: false,
        allowedFileExtensions: ['jpg', 'png', 'gif'],
        maxFileCount: 5,
    }).on('fileuploaded', function (event, data, id, index) {
        var ret = data.response;
        if (0 != ret.errno) {
            toastr.error('上传失败', '', {positionClass: 'toast-bottom-center'});
        }
        toastr.success('上传成功', '', {positionClass: 'toast-bottom-center'});
        console.log(data.response);
        pictureUrl = ret.data.url;
        console.log(pictureUrl);
        //pictureUrl = "http://" + ret.data.url;
    }).on("filebatchselected", function (event, files) {
        pictureUrl = '';
        $("#" + id).fileinput("upload");
    });
}

/*
 function init(){
 $("#img").fileinput({
 uploadUrl: "/common/uploadimage", // server upload action
 showUpload: false,
 uploadAsync: true,
 showPreview: false,
 allowedFileExtensions: ['jpg', 'png', 'gif'],
 maxFileCount: 5,
 }).on('fileuploaded', function(event, data, id, index) {
 var ret = data.response;
 if(0 !=ret.errno){
 toastr.error('上传失败','',{positionClass: 'toast-bottom-center'});
 }
 toastr.success('上传成功','',{positionClass: 'toast-bottom-center'});
 console.log(data.response);
 pictureUrl = ret.data.url;
 myData.append('img',pictureUrl);
 console.log(pictureUrl);
 //pictureUrl = "http://" + ret.data.url;
 }).on("filebatchselected", function (event, files) {
 $("#img").fileinput("upload");
 });
 }

 function addCategory(){
 var btn = $("#confirm");
 btn.click(function(){
 var flag = true;

 if($("#category_name").val() == '' || $("#keywords").val() == '' || $("#cat_desc").val() == ''){
 flag = false;
 }
 myData.append('cat_desc',$("#cat_desc").val());
 myData.append('parent_id',$("#parent_id").find("option:selected").val());
 if(false === flag){
 //toastr.error('请输入增加优惠券所需要的全部信息');
 toastr.error('请输入增加分类所需要的全部信息','',{positionClass: 'toast-bottom-center'});
 return false;
 }
 $("#addcategory").find("input[type='text']").each(function () {
 console.log($(this).attr('id'),$(this).val());
 if ($(this).val() != "") {
 var param = $(this).attr('id');
 var value = $(this).val();
 myData.append(param,value);
 //console.log(value);

 }
 })



 $.ajax({
 url : '/goods/addgoodscategory',
 timeout : 100000,
 type : 'post',
 processData: false,
 contentType: false,
 dataType : 'json',
 data : myData,
 success : function (rs) {
 if (rs.errno != 0) {
 toastr.error(rs.errmsg,'',{positionClass: 'toast-bottom-center'});
 }
 if (rs.errno == 0){
 toastr.success(rs.errmsg);
 window.location.reload();
 $('#myModal').modal('hide');
 }
 },
 error : function () {
 toastr.error('系统错误','',{positionClass: 'toast-bottom-center'});
 }
 });
 //alert(test);
 });
 }
 */
/**
 $(document).ready(function() {

    $("#logo").fileinput({
        showCaption: false,
        showUpload : false,
        showRemove : false,
    });
    var btn = $("#confirm");
    btn.click(function(){
        var flag = true;
        $("#addbrand").find("input[type='text']").each(function () {
            console.log($(this).val());
            if ($(this).val() == "") {
                flag = false;
                return false;
            }
        })
        if(false === flag){
            //toastr.error('请输入增加优惠券所需要的全部信息');
            toastr.error('请输入增加优惠券所需要的全部信息','',{positionClass: 'toast-bottom-center'});
            return false;
        }
        var brandName = $('#brand_name').val();
        var isShow = $('#is_show').val();
        var displayOrder = $('#display_order').val();
        //var logoFile = $('#logo').val();
        var myData = new FormData();
        myData.append('brand_name',brandName);
        myData.append('is_show',isShow);
        myData.append('display_order',displayOrder);
        myData.append('logo',$("#logo")[0]);
        console.log(myData);

        $.ajax({
            url : '/home/shop/addbrand',
            timeout : 100000,
            type : 'post',
            processData: false,
            contentType: false,
            dataType : 'json',
            data : myData,
            success : function (rs) {
                if (rs.errno != 0) {
                    toastr.error(rs.errmsg,'',{positionClass: 'toast-bottom-center'});
                }
                if (rs.errno == 0){
                    toastr.success(rs.errmsg);
                    window.location.reload();
                    $('#myModal').modal('hide');
                }
            },
            error : function () {
                toastr.error('系统错误','',{positionClass: 'toast-bottom-center'});
            }
        });
        //alert(test);
    });

});


 function test(initialImg){
    $("#editimg").fileinput('refresh',{
        uploadUrl: "/common/uploadimage", // server upload action
        showUpload: false,
        uploadAsync: true,
        showPreview: true,
        allowedFileExtensions: ['jpg', 'png', 'gif'],
        maxFileCount: 1,
        initialPreviewAsData: true,
        overwriteInitial: true,
        initialPreview: initialImg,
        //defaultPreviewContent: '<img src="http://manshe-app.oss-cn-beijing.aliyuncs.com/default_avatar.jpg" alt="Your Avatar" style="width:160px">',

    }).on('fileuploaded', function(event, data, id, index) {
        var ret = data.response;
        if(0 !=ret.errno){
            toastr.error('上传失败','',{positionClass: 'toast-bottom-center'});
        }else{
            toastr.success('上传成功111','',{positionClass: 'toast-bottom-center'});
            console.log(data.response);
            pictureUrl = ret.data.url;
            console.log(pictureUrl);
            //pictureUrl = "http://" + ret.data.url;
        }

    }).on("filebatchselected", function (event, files) {
        pictureUrl = '';
        $("#editimg").fileinput("upload");
    });
}

 **/